<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\traits\JsonResponse;
use think\exception\ValidateException;
use think\Request;
use app\model\Topic as TopicModel;
use app\model\Comment as CommentModel;

class Comment extends BaseController {
    use JsonResponse;
    protected $middleware = [
        'auth_jwt' => ['only' => ['save','delete','replyComment']],
    ];
    public function index($topic_id) {
        $topic  = TopicModel::findOrEmpty($topic_id);
        if(!$topic->isEmpty()){
         $comments = $topic->comments()->with(['user','topic','replyComments','belongToComment','replyUser'])->select();
            return $this->jsonSuccess($comments);
        }else{
            return $this->jsonFail();
        }
    }

    public function save(Request $request,$topic_id) {
        try {
            validate([
                'content|评论内容'  => 'require|max:20000|min:3',
            ])->batch()->check($request->post());
            $topic = TopicModel::findOrEmpty($topic_id);
            if(!$topic->isEmpty()){
               $comment =  $topic->comments()->save(
                    [
                        'content'=>$request->post('content'),
                        'user_id'=>$this->user_id
                    ],
                );
                $comment = CommentModel::with(['user','topic','replyComments','belongToComment','replyUser'])->find($comment->id);
                return $this->jsonSuccess($comment,'新增评论成功',201);
            }else{
                return $this->jsonFail();
            }
        } catch (ValidateException $e) {
            return $this->jsonFail($e->getError(),'输入信息不合法',422);
        }
    }
    public function replyComment(Request $request,$topic_id,$comment_id){
        try {
            validate([
                'content|评论内容'  => 'require|max:20000|min:3',
            ])->batch()->check($request->post());
            $topic = TopicModel::findOrEmpty($topic_id);
            $comment = CommentModel::findOrEmpty($comment_id);
            if(!$topic->isEmpty() && !$comment->isEmpty()){
               $comment = $topic->comments()->save([
                    'content' => $request->post('content'),
                    'user_id' => $this->user_id,
                    'reply_comment_id' => $comment->relpy_comment_id ?: $comment->id,
                    'reply_user_id' => $comment->user_id
                ]);
               $comment = CommentModel::with(['user','topic','replyComments','belongToComment','replyUser'])->find($comment->id);
               return $this->jsonSuccess($comment,'评论发表成功',201);
            }else{
                return $this->jsonFail();
            }
        } catch (ValidateException $e) {
            return $this->jsonFail($e->getError(),'输入信息不合法',422);
        }

    }
    public function delete($id) {
        //
    }
}
